<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 返回按钮 -->
    <div class="bg-white border-b">
      <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <el-button @click="goBack" :icon="ArrowLeft" class="mb-0">
          返回控制台
        </el-button>
      </div>
    </div>

    <div class="max-w-4xl mx-auto py-6 sm:px-6 lg:px-8">
      <div class="px-4 py-6 sm:px-0">
        <!-- 页面标题 -->
        <div class="mb-8">
          <h1 class="text-3xl font-bold text-gray-900">个人资料</h1>
          <p class="mt-2 text-sm text-gray-600">管理您的账户信息和设置</p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <!-- 左侧：头像和基本信息 -->
          <div class="lg:col-span-1">
            <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6">
              <!-- 头像上传 -->
              <div class="text-center mb-6">
                <div class="relative inline-block">
                  <el-avatar :size="100" :src="userProfile?.avatarUrl || userAvatar" class="mb-4">
                    <el-icon :size="40"><User /></el-icon>
                  </el-avatar>
                  <el-upload
                    :show-file-list="false"
                    :before-upload="handleAvatarUpload"
                    accept="image/*"
                    class="absolute bottom-0 right-0"
                  >
                    <el-button size="small" circle :icon="Camera" class="shadow-md" />
                  </el-upload>
                </div>
                <h3 class="text-lg font-semibold text-gray-900">{{ userProfile?.username || '用户' }}</h3>
                <p class="text-sm text-gray-500">{{ userProfile?.email }}</p>
              </div>

              <!-- 账户统计 -->
              <div class="space-y-4">
                <div class="flex justify-between items-center">
                  <span class="text-sm text-gray-600">注册时间</span>
                  <span class="text-sm font-medium">{{ userProfile?.createdAt ? formatDate(userProfile.createdAt) : '加载中...' }}</span>
                </div>
                <div class="flex justify-between items-center">
                  <span class="text-sm text-gray-600">最后登录</span>
                  <span class="text-sm font-medium">{{ userProfile?.lastLoginTime ? formatDate(userProfile.lastLoginTime) : '加载中...' }}</span>
                </div>
                <div class="flex justify-between items-center">
                  <span class="text-sm text-gray-600">登录次数</span>
                  <span class="text-sm font-medium">{{ userProfile?.loginCount ?? '加载中...' }}</span>
                </div>
                <div class="flex justify-between items-center">
                  <span class="text-sm text-gray-600">对话总数</span>
                  <span class="text-sm font-medium">{{ userProfile?.totalConversations ?? '加载中...' }}</span>
                </div>
                <div class="flex justify-between items-center">
                  <span class="text-sm text-gray-600">账户状态</span>
                  <el-tag 
                    :type="userProfile?.status === 1 ? 'success' : 'danger'" 
                    size="small"
                    v-if="userProfile"
                  >
                    {{ userProfile.status === 1 ? '正常' : '禁用' }}
                  </el-tag>
                  <span v-else class="text-sm text-gray-500">加载中...</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧：详细信息编辑 -->
          <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-6">基本信息</h3>
              
              <el-form
                ref="profileFormRef"
                :model="profileForm"
                :rules="profileRules"
                label-width="80px"
                size="large"
              >
                <!-- 用户名 -->
                <el-form-item label="用户名" prop="username">
                  <el-input
                    v-model="profileForm.username"
                    placeholder="请输入用户名"
                    clearable
                  />
                </el-form-item>

                <!-- 性别 -->
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="profileForm.gender" placeholder="请选择性别" class="w-full">
                    <el-option label="未知" :value="0" />
                    <el-option label="男" :value="1" />
                    <el-option label="女" :value="2" />
                  </el-select>
                </el-form-item>

                <!-- 年龄 -->
                <el-form-item label="年龄" prop="age">
                  <el-input-number
                    v-model="profileForm.age"
                    :min="1"
                    :max="120"
                    placeholder="请输入年龄"
                    class="w-full"
                  />
                </el-form-item>

                <!-- 邮箱 -->
                <el-form-item label="邮箱" prop="email">
                  <div class="flex space-x-3">
                    <el-input
                      v-model="profileForm.email"
                      placeholder="请输入邮箱地址"
                      clearable
                      class="flex-1"
                    />
                    <el-button v-if="!userInfo?.email" type="primary" plain>
                      验证邮箱
                    </el-button>
                  </div>
                </el-form-item>

                <!-- 手机号 -->
                <el-form-item label="手机号" prop="phone">
                  <div class="flex space-x-3">
                    <el-input
                      v-model="profileForm.phone"
                      placeholder="请输入手机号码"
                      clearable
                      class="flex-1"
                    />
                    <el-button v-if="!userInfo?.phone" type="primary" plain>
                      绑定手机
                    </el-button>
                  </div>
                </el-form-item>

                <!-- 保存按钮 -->
                <el-form-item>
                  <el-button
                    type="primary"
                    :loading="loading"
                    @click="handleSave"
                    class="w-full"
                  >
                    保存修改
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 密码修改 -->
            <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6 mt-6">
              <h3 class="text-lg font-semibold text-gray-900 mb-6">修改密码</h3>
              
              <el-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="passwordRules"
                label-width="80px"
                size="large"
              >
                <!-- 当前密码 -->
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input
                    v-model="passwordForm.oldPassword"
                    type="password"
                    placeholder="请输入当前密码"
                    show-password
                    clearable
                  />
                </el-form-item>

                <!-- 新密码 -->
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="passwordForm.newPassword"
                    type="password"
                    placeholder="请输入新密码"
                    show-password
                    clearable
                  />
                </el-form-item>

                <!-- 密码强度指示器 -->
                <div v-if="passwordForm.newPassword" class="mb-4 ml-20">
                  <div class="flex items-center justify-between text-xs mb-1">
                    <span class="text-gray-500">密码强度</span>
                    <span :style="{ color: passwordStrength.color }">{{ passwordStrength.text }}</span>
                  </div>
                  <div class="w-full bg-gray-200 rounded-full h-2">
                    <div
                      class="h-2 rounded-full transition-all duration-300"
                      :style="{
                        width: `${(passwordStrength.level / 5) * 100}%`,
                        backgroundColor: passwordStrength.color
                      }"
                    />
                  </div>
                </div>

                <!-- 确认新密码 -->
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="passwordForm.confirmPassword"
                    type="password"
                    placeholder="请确认新密码"
                    show-password
                    clearable
                  />
                </el-form-item>

                <!-- 修改密码按钮 -->
                <el-form-item>
                  <el-button
                    type="danger"
                    :loading="passwordLoading"
                    @click="handleChangePassword"
                    class="w-full"
                  >
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 危险操作 -->
            <div class="bg-white rounded-xl shadow-lg border border-red-200 p-6 mt-6">
              <h3 class="text-lg font-semibold text-red-900 mb-4">危险操作</h3>
              <div class="space-y-4">
                <div class="flex justify-between items-center">
                  <div>
                    <h4 class="text-sm font-medium text-gray-900">清除其他设备登录</h4>
                    <p class="text-xs text-gray-500">登出所有其他设备上的会话</p>
                  </div>
                  <el-button type="warning" plain size="small">
                    清除会话
                  </el-button>
                </div>
                <div class="flex justify-between items-center">
                  <div>
                    <h4 class="text-sm font-medium text-gray-900">删除账户</h4>
                    <p class="text-xs text-gray-500">永久删除您的账户和所有数据</p>
                  </div>
                  <el-button type="danger" plain size="small">
                    删除账户
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ArrowLeft, User, Camera } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { validators, getPasswordStrength } from '@/utils/auth'
import type { UserInfo } from '@/types'
import { 
  getUserProfile, 
  updateUserProfile, 
  uploadUserAvatar, 
  updatePassword,
  getLoginHistory,
  type UserProfile,
  type UserProfileUpdateDTO,
  type PasswordUpdateDTO
} from '@/api/user'

// 路由和状态
const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const profileFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)
const passwordLoading = ref(false)

// 计算属性
const userInfo = computed(() => authStore.userInfo)
const userDisplayName = computed(() => authStore.userDisplayName)
const userAvatar = computed(() => authStore.userAvatar)

// 用户详细信息
const userProfile = ref<UserProfile | null>(null)

// 个人信息表单
const profileForm = reactive({
  username: '',
  email: '',
  phone: '',
  gender: 0,
  age: undefined as number | undefined
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码强度
const passwordStrength = computed(() => {
  return getPasswordStrength(passwordForm.newPassword)
})

// 表单验证规则
const profileRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!validators.username(value)) {
          callback(new Error('用户名只能包含字母、数字和下划线'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    {
      validator: (rule, value, callback) => {
        if (value && !validators.email(value)) {
          callback(new Error('请输入有效的邮箱地址'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    {
      validator: (rule, value, callback) => {
        if (value && !validators.phone(value)) {
          callback(new Error('请输入有效的手机号码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  age: [
    {
      validator: (rule, value, callback) => {
        if (value && (value < 1 || value > 120)) {
          callback(new Error('年龄必须在1-120之间'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度不能少于8个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!validators.password(value)) {
          callback(new Error('密码必须包含字母和数字'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

/**
 * 返回控制台
 */
const goBack = () => {
  router.push('/dashboard')
}

/**
 * 加载用户详细信息
 */
const loadUserProfile = async () => {
  try {
    const response = await getUserProfile()
    console.log('🔍 API响应:', response)
    console.log('🔍 response类型:', typeof response)
    console.log('🔍 response.id:', response?.id)
    console.log('🔍 response.data:', response?.data)
    
    // 检查响应结构 - 拦截器已经处理了响应
    if (response && typeof response === 'object' && response.id) {
      // response 本身就是用户数据对象
      console.log('✅ 使用response直接作为数据')
      userProfile.value = response
      initFormData()
    } else if (response.data && typeof response.data === 'object' && response.data.id) {
      // response.data 是用户数据对象
      console.log('✅ 使用response.data作为数据')
      userProfile.value = response.data
      initFormData()
    } else if (response.data && response.data.code === 200 && response.data.data) {
      // 包装格式: { code: 200, message: "操作成功", data: {...} }
      console.log('✅ 使用response.data.data作为数据')
      userProfile.value = response.data.data
      initFormData()
    } else {
      console.error('❌ 无法识别响应格式:', response)
      ElMessage.error('响应数据格式不正确')
    }
  } catch (error) {
    console.error('加载用户资料失败:', error)
    ElMessage.error('加载用户信息失败')
  }
}

/**
 * 初始化表单数据
 */
const initFormData = () => {
  if (userProfile.value) {
    profileForm.username = userProfile.value.username || ''
    profileForm.email = userProfile.value.email || ''
    profileForm.phone = userProfile.value.phone || ''
    profileForm.gender = userProfile.value.gender || 0
    profileForm.age = userProfile.value.age || undefined
    
    // 清除表单验证状态
    nextTick(() => {
      if (profileFormRef.value) {
        profileFormRef.value.clearValidate()
      }
    })
  }
}

/**
 * 处理头像上传
 */
const handleAvatarUpload = async (file: File) => {
  try {
    // 文件大小检查
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('头像文件大小不能超过5MB')
      return false
    }

    // 文件类型检查
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件')
      return false
    }

    const response = await uploadUserAvatar(file)
    console.log('🔍 头像上传响应:', response)
    
    // 后端返回格式: { code: 200, message: "头像URL", data: "头像上传成功" }
    if (response && response.message) {
      userProfile.value!.avatarUrl = response.message
      ElMessage.success('头像上传成功')
    } else if (response.data && response.data.avatarUrl) {
      // 兼容其他格式
      userProfile.value!.avatarUrl = response.data.avatarUrl
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error('头像上传失败：无法获取头像URL')
    }
    return false // 阻止默认上传
  } catch (error) {
    console.error('Avatar upload failed:', error)
    ElMessage.error('头像上传失败')
    return false
  }
}

/**
 * 保存个人信息
 */
const handleSave = async () => {
  if (!profileFormRef.value) return

  try {
    await profileFormRef.value.validate()
    
    loading.value = true

    // 只更新有值的字段
    const updateData: UserProfileUpdateDTO = {
      username: profileForm.username,
      gender: profileForm.gender,
      age: profileForm.age
    }

    // 只有当邮箱不为空时才更新
    if (profileForm.email && profileForm.email.trim()) {
      updateData.email = profileForm.email
    }

    // 只有当手机号不为空时才更新
    if (profileForm.phone && profileForm.phone.trim()) {
      updateData.phone = profileForm.phone
    }

    const response = await updateUserProfile(updateData)
    userProfile.value = response.data
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    console.error('Save profile failed:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

/**
 * 修改密码
 */
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    
    passwordLoading.value = true

    const updateData: PasswordUpdateDTO = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    }

    await updatePassword(updateData)
    ElMessage.success('密码修改成功')
    
    // 清空表单
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error) {
    console.error('Change password failed:', error)
    ElMessage.error('密码修改失败，请检查原密码是否正确')
  } finally {
    passwordLoading.value = false
  }
}

/**
 * 格式化日期
 */
const formatDate = (dateString?: string) => {
  if (!dateString) return '未知'
  
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) {
      return '未知'
    }
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '未知'
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
/* 自定义样式 */
.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  border-radius: 8px;
}

.el-button {
  border-radius: 8px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .lg\:col-span-1,
  .lg\:col-span-2 {
    grid-column: span 1;
  }
}

@media (max-width: 640px) {
  .max-w-4xl {
    padding: 0 16px;
  }
  
  .bg-white {
    padding: 24px;
  }
  
  .flex.space-x-3 {
    flex-direction: column;
    space-x: 0;
  }
  
  .flex.space-x-3 > * + * {
    margin-left: 0;
    margin-top: 12px;
  }
}

/* 动画效果 */
.transition-all {
  transition: all 0.3s ease;
}

/* 头像上传悬停效果 */
.el-upload:hover .el-button {
  transform: scale(1.1);
}
</style>
